# -*- coding: utf-8 -*-
import android
import os
droid = android.Android()
address = 'te ligou'

try:
    with open('/sdcard/.message_notification','r') as arq:
        address = arq.read()
except IOError:
    pass

def get_best_contact_name(contacts,phone_number):
    dic = {}
    for contact in contacts:
        dic[contact['data1']] = contact['display_name']
    
    for x in range(len(phone_number),7,-1):
        num = phone_number[-x:]    
        if dic.has_key(num):
           return dic[num]
    return contacts[-1]['display_name']

def get_contacts(phone_numbers):
    for phone_number in phone_numbers:
        small_number = phone_number[-8:]
        contacts = droid.queryContent('content://com.android.contacts/data/phones',['display_name','data1'],'data1 like "%'+small_number+'%"',None,None).result
        if len(contacts) == 0:
            yield phone_number,phone_number
        else:
            yield phone_number,get_best_contact_name(contacts,phone_number)

def get_messages():
    unread_messages = droid.smsGetMessages(False)
    opts = []
    for message in unread_messages.result:
        if message['address'].lower() != address.lower():
            continue
        
        message_text = message['body']
        
        phone_numbers =  [ x for x in message_text.split(' ') if x.isdigit() and len(x) > 7 ]
        
        contacts = get_contacts(phone_numbers)
        
        for phone_number,contact in contacts:
            message_text=message_text.replace(phone_number,contact)
            opts.append({
                'numero':phone_number,
                'contato':contact,
                'mensagem':message_text,
                'mensagem_id':message['_id']
            })
        
    return opts

def main_menu():
    opts = get_messages()
    droid.dialogCreateInput('Lembrete de ligações');
    droid.dialogSetNeutralButtonText('Opções')
    droid.dialogSetNegativeButtonText('Sair')
    droid.dialogSetItems([ "%s (%s)" %(opt['contato'],opt['numero']) for opt in opts ])
    droid.dialogShow()

    result = droid.dialogGetResponse().result

    if result.has_key('item'):
        return menu_contato(opts[result['item']])
    
    if result.has_key('which'):
        if result['which'] == 'negative':
            return False
        if result['which'] == 'neutral':
            menu_opcoes()
    return True

def menu_opcoes():
    global address
    droid.dialogCreateInput('Lembrete de ligações','Número do remetente',address);
    droid.dialogSetPositiveButtonText('OK')    
    droid.dialogSetNegativeButtonText('Cancelar')
    droid.dialogShow()

    result = droid.dialogGetResponse().result
    if result['which'] == 'positive':
        with open('/sdcard/.message_notification','w') as arq:
            arq.write(result['value'])
        address = result['value']       
    
def menu_contato(contato):
    droid.dialogCreateAlert('Lembrete de ligações',contato['mensagem']);
    droid.dialogSetPositiveButtonText('Retornar ligação')
    droid.dialogSetNeutralButtonText('Remover SMS')
    droid.dialogSetNegativeButtonText('Voltar')
    droid.dialogShow()

    result = droid.dialogGetResponse().result
    if result['which'] == 'positive':
        droid.phoneCallNumber(contato['numero'])
        return False
    if result['which'] == 'neutral':
        droid.smsDeleteMessage(contato['mensagem_id'])
    return True

loop = True
while loop:
    loop=main_menu()

